package org.fzu.ercha.wuta.Activity;

import android.app.AlertDialog;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import org.fzu.ercha.wuta.Adapter.WutaPagerAdapter;
import org.fzu.ercha.wuta.Entity.Audio;
import org.fzu.ercha.wuta.Fragment.LyricFragment;
import org.fzu.ercha.wuta.Fragment.SongFragment;
import org.fzu.ercha.wuta.MyApplication;
import org.fzu.ercha.wuta.R;
import org.fzu.ercha.wuta.Service.MainService;
import org.fzu.ercha.wuta.Util.LogUtil;
import org.fzu.ercha.wuta.Util.MediaUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;


/**
 * Created by ercha on 2017/1/26.
 */

public class MainActivity extends FragmentActivity implements View.OnClickListener, ServiceConnection {
    private FragmentPagerAdapter mPagerAdapter = null;
    private ViewPager mViewPager = null;
    private List<Fragment> mFragmentList = null;

    private Button addButton = null;

    private String curPath = "/sdcard";

    private Context self;

    private MainService mMainService = null;

    private boolean isPlay = false;

    private Button playBtn = null, lastBtn = null, nextBtn = null, modelBtn = null;

    private SeekBar seekBar = null;
    private TextView currentTimeTextView = null, totalTimeTextView = null;

    private Timer timer = null;

    private boolean isAutoChangeSeekBar = true;

    private TextView titleTextView = null, artistTextView = null;

    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        self = this;

        mFragmentList = new ArrayList<>();
        SongFragment songFragment = new SongFragment();
        songFragment.setOnSongListChangedListener(new SongFragment.OnSongListChangedListener() {
            @Override
            public void onSongDeleted() {
                Audio audio = mMainService.getCurrentAudio();
                if(!titleTextView.getText().toString().equals(audio.getTitle())){
                    titleTextView.setText(audio.getTitle());
                    artistTextView.setText(audio.getArtist());
                }
            }
        });
        songFragment.setOnClickListListener(new SongFragment.OnClickListListener() {
            @Override
            public void onClick(Audio audio) {
                mMainService.start(audio);
            }
        });
        mFragmentList.add(songFragment);
        mFragmentList.add(new LyricFragment());

        mPagerAdapter = new WutaPagerAdapter(getSupportFragmentManager(), mFragmentList);
        mViewPager = (ViewPager)findViewById(R.id.viewPager);
        mViewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener(){
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                // This space for rent
            }

            @Override
            public void onPageSelected(int position) {
                // This space for rent
                switch (position){
                    case 0:
                        findViewById(R.id.messageLayout).setVisibility(View.GONE);
                        break;
                    case 1:
                        findViewById(R.id.messageLayout).setVisibility(View.VISIBLE);

                        break;
                    default:
                        findViewById(R.id.messageLayout).setVisibility(View.GONE);
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                // This space for rent
            }
        });
        mViewPager.setAdapter(mPagerAdapter);

        addButton = (Button)findViewById(R.id.addButton);
        addButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                openCurDir(curPath);
            }
        });

        modelBtn = (Button)findViewById(R.id.modelBtn);
        lastBtn = (Button)findViewById(R.id.lastBtn);
        playBtn = (Button)findViewById(R.id.playBtn);
        nextBtn = (Button)findViewById(R.id.nextBtn);
        modelBtn.setOnClickListener(this);
        lastBtn.setOnClickListener(this);
        playBtn.setOnClickListener(this);
        nextBtn.setOnClickListener(this);

        seekBar = (SeekBar)findViewById(R.id.seekBar);
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            /**
             * SeekBar 滚动时的回调函数
             * @param seekBar
             * @param progress
             * @param fromUser
             */
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                currentTimeTextView.setText(ss2MMss(seekBar.getProgress()));
            }

            /**
             * SeekBar 开始滚动的回调函数
             * @param seekBar
             */
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                isAutoChangeSeekBar = false;
            }

            /**
             * SeekBar 停止滚动的回调函数
             * @param seekBar
             */
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                isAutoChangeSeekBar = true;
                //调整当前播放进度
                mMainService.seekTo(seekBar.getProgress());
            }
        });

        currentTimeTextView = (TextView)findViewById(R.id.currentTimeText);
        totalTimeTextView = (TextView)findViewById(R.id.totalTimeText);

        titleTextView = (TextView)findViewById(R.id.titleTextView);
        artistTextView = (TextView)findViewById(R.id.artistTextView);

        Audio curAudio = MyApplication.getCurrentAudio();
        if(curAudio != null){
            totalTimeTextView.setText(ss2MMss(curAudio.getDuration() / 1000));
            titleTextView.setText(curAudio.getTitle());
            artistTextView.setText(curAudio.getArtist());
        }

        //Service
        startMainService();
        bindMainService();
    }

    private void openCurDir(String curPath){
        File f = new File(curPath);
        File[] file = f.listFiles();
        final List<Map<String,Object>> listItem = new ArrayList<>();

        if(!curPath.equals("/")){//如果不是根目录的话就在要显示的列表中加入此项
            Map<String,Object> map1=new HashMap<>();
            map1.put("name", "返回上一级目录");
            map1.put("image", R.drawable.back02);
            map1.put("path",f.getParent());
            map1.put("isDire", true);
            listItem.add(map1);
        }

        if(file != null){//必须判断 否则目录为空的时候会报错
            for(int i = 0; i < file.length; i++){
                Map<String,Object> map=new HashMap<>();
                map.put("name", file[i].getName());
                map.put("image", (file[i].isDirectory()) ? R.drawable.folder : R.drawable.doc);
                map.put("path",file[i].getPath());
                map.put("isDire", file[i].isDirectory());
                listItem.add(map);
            }
        }

        SimpleAdapter adapter = new SimpleAdapter(MainActivity.this,listItem,R.layout.adapter_filepath,
                new String[]{"name","image"},new int[]{R.id.adapter_filename,R.id.adapter_image});

        final AlertDialog.Builder b =new AlertDialog.Builder(MainActivity.this);

        b.setAdapter(adapter, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface arg0, int arg1) {
                // TODO Auto-generated method stub
                if((Boolean) listItem.get(arg1).get("isDire")){
                    openCurDir((String)listItem.get(arg1).get("path"));
                }else{
//                    fileDire.setText((String)listItem.get(arg1).get("path"));
                    String filePath = (String)listItem.get(arg1).get("path");
                    Toast.makeText(self, filePath, Toast.LENGTH_SHORT).show();

                }
            }
        });
        b.show();
    }

    @Override
    public void onDestroy(){
        super.onDestroy();
//        unbindMainService();

        MyApplication.saveAudioMessage();
    }

    /**
     * 启动服务
     */
    public void startMainService () {
        Intent it = new Intent (this, MainService.class);
        startService(it);
    }

    /**
     * 停止服务
     */
    public void stopMainService () {
        Intent it = new Intent(this, MainService.class);
        stopService(it);
    }

    private void bindMainService () {
        Intent it = new Intent (this, MainService.class);
        this.bindService(it, this, Service.BIND_AUTO_CREATE);
    }

    private void unbindMainService () {
        this.unbindService(this);
    }

    /**
     * 与 Service 成功绑定时调用
     * @param name
     * @param service
     */
    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        if (service instanceof MainService.ServiceBinder) {
            MainService.ServiceBinder binder = (MainService.ServiceBinder)service;
            mMainService = binder.getService();
            this.registerServiceCallback();
        }
    }

    private void registerServiceCallback(){
        mMainService.setOnPlaybackListener(new MainService.OnPlaybackListener() {
            @Override
            public void onStateChanged(int state) {
                switch (state){
                    case MainService.State.IDLE:
                    case MainService.State.PAUSED:
                    case MainService.State.COMPLETED:
                        isPlay = false;
                        playBtn.setText("play");
                        if(timer != null){
                            timer.cancel();
                            timer.purge();
                            timer = null;
                        }
                        break;
                    case MainService.State.PREPARING:
                        isPlay = true;
                        playBtn.setText("pause");
                        break;
                    case MainService.State.STARTED:
                        isPlay = true;
                        playBtn.setText("pause");
                        titleTextView.setText(mMainService.getCurrentAudio().getTitle());
                        artistTextView.setText(mMainService.getCurrentAudio().getArtist());
                        //更新时长；将进度条最大值设置为秒数
                        int totalTime = mMainService.getDuration();
                        seekBar.setMax(totalTime);
                        totalTimeTextView.setText(ss2MMss(totalTime));

                        //定时更新进度条
                        timer = new Timer();
                        timer.schedule(new TimerTask() {
                            @Override
                            public void run() {
                                LogUtil.i("Timer", "正在执行定时任务!");
                                if(isAutoChangeSeekBar){
                                    seekBar.setProgress(mMainService.getCurrentPosition());
                                }
                            }
                        }, 0, 1000);
                        break;
                }
            }
        });
    }

    private String ss2MMss(int ss){
        int mm = ss / 60;
        ss %= 60;
        return (mm<10?"0":"") + mm + ":" + (ss<10?"0":"") + ss%60;
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
        Toast.makeText(this, "onServiceDisconnected name=" + name, Toast.LENGTH_LONG).show();
    }

    @Override
    public void onClick(View view){
        switch (view.getId()){
            case R.id.lastBtn:
                mMainService.last();
                break;

            case R.id.playBtn:
                if(isPlay){
                    mMainService.pause();
                } else{
                    mMainService.start();
                }
                break;

            case R.id.nextBtn:
                mMainService.next();
                break;
        }
    }
}
